package com.mql.onlinechatsystem.Interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * Describes: WebSocket握手拦截器
 * Auth: Eric
 */
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
    private final static Logger LOGGER = LoggerFactory.getLogger(WebSocketHandshakeInterceptor.class);

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            String path = request.getURI().getPath();
            if(requestIsValid(path)){
                String[] params = getParams(path);
                attributes.put("WEBSOCKET_AUTH", params[0]);
                attributes.put("WEBSOCKET_PID", params[1]);
                attributes.put("WEBSOCKET_SN", params[2]);
                attributes.put("WEBSOCKET_OPENID", params[3]);
                attributes.put("WEBSOCKET_FIRSTONE","yes");
            }
        }
        System.out.println("================Before Handshake================");
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        System.out.println("================After Handshake================");
        if(e!=null) e.printStackTrace();
        System.out.println("================After Handshake================");
    }

    private boolean requestIsValid(String url){
        //在这里可以写上具体的鉴权逻辑
        boolean isvalid = false;
        if(StringUtils.isNotEmpty(url)
                && url.startsWith("/netgate/")
                && url.split("/").length==6){
            isvalid = true;
        }
        return isvalid;
    }

    private String[] getParams(String url){
        url = url.replace("/netgate/","");
        return url.split("/");
    }
}

